package com.sirdc.modules.sys.web.HardWork;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.sys.util.ExportExcel;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.filter.MessageListFilter;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.responseModel.MessageModel;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.node.filter.NodeNewschedulesFilter;
import net.huashitong.oversee.filter.CoordinateFilter;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.service.CoordinateService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.entity.Message;
import net.huashitong.user.filter.BnpUserFilter;
import net.huashitong.user.filter.MessageFilter;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.user.service.MessageService;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sysMessageManger")
public class SysMessageMangerController extends JsonBaseController {

    @Override
    protected String getView(String s) {
        return "/modules/sysMessageManager/" + s;
    }

    @Autowired
    private MessageService ms;
    @Autowired
    private NewProjectsService newProjectsService;
    @Autowired
    private BnpUserService bnpUserService;

    @ModelAttribute("headType")
    public String returnHeadType() {
        return "消息管理模块";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initPage(HttpServletRequest request, Model model) {
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bnpUser)) {
            return "/modules/login/login";
        }
        int myTaskNum = (int) WebUtils.getSessionAttribute(request, "myTaskNum");
        int quetionNum = (int) WebUtils.getSessionAttribute(request, "quetionNum");
        model.addAttribute("myTaskNum", myTaskNum);
        model.addAttribute("quetionNum", quetionNum);
        //待办任务个数
        int nodeCount = (int) WebUtils.getSessionAttribute(request, "nodeCount");
        model.addAttribute("nodeCount", nodeCount);

        int myTackTaskNum = (int) WebUtils.getSessionAttribute(request, "myTackTaskNum");
        model.addAttribute("myTackTaskNum", myTackTaskNum);

        model.addAttribute("leftType", "报表模块");
        model.addAttribute("user",bnpUser);
        return getView("query");
    }

    //初始化数据
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid query(@ModelAttribute MessageFilter filter){

        List<Message> list = ms.getMessageInfo(filter);
        for(Message l:list){
            //峰会时期手机号码加密
            /*if(l.getPhone().length()==11){
                String newPhone = l.getPhone().substring(0,3)+"****"+l.getPhone().substring(7,11);
                l.setPhone(newPhone);
            }*/
            if ("业主单位".equals(l.getResDept()) ||
                    "中介机构".equals(l.getResDept()) ||
                    "业主、中介机构".equals(l.getResDept())){
                NewProjectsFilter newProjectsFilter=new NewProjectsFilter();
                newProjectsFilter.setName(l.getProjectName());
                List<NewProjects> projectInfo = newProjectsService.getProjectInfo(newProjectsFilter);
                if(ObjectUtils.isNotBlank(projectInfo)){
                    l.setResDept(projectInfo.get(0).getResDept());
                }
            }
        }
        return coverJqGrid(filter, list);
    }

    @RequestMapping("/filter")
    public String filter(@ModelAttribute MessageFilter filter, Model model) {
        //查询所有单位
        List<String> branchs = bnpUserService.queryAllBranchs();
        model.addAttribute("branchs", branchs);
        model.addAttribute("messageFilter", filter);
        return getView("filter");
    }

    @ResponseBody
    @RequestMapping(value = "/download")
    public String download(@RequestParam("beginDate") String beginDate,
                           @RequestParam("endDate") String endDate,
                           HttpServletRequest request,
                           HttpServletResponse response) {
        //用于导出的数据集合
        List<MessageModel> messageList = ms.getMessageByDate(beginDate, endDate);
        if (messageList.size() == 0) {
            return "无相关记录";
        }

        //临时文件
        File tempFile = null;
        try {
            //Excel导出工具类
            ExportExcel<MessageModel> ex = new ExportExcel<MessageModel>();
            //导出的标题列
            String[] headers = {"项目名", "类别", "责任单位", "收件人", "电话号码", "短信内容", "日期", "时间"};

            //要保存的文件名
            String filename = "Message_" + beginDate + "_" + endDate + ".xls";
            //要保存的根目录
            String rootDir = request.getSession().getServletContext().getRealPath("/");
            //要保存的目录路径
            String path = rootDir + File.separator + "tempfile";
            File saveDir = new File(path);
            if (!saveDir.exists()) {
                // 如果文件不存在则创建文件夹
                saveDir.mkdirs();
            }
            //文件路径
            path = path + File.separator + filename;
            //初始化临时文件
            tempFile = new File(path);
            //输出流
            OutputStream out = new FileOutputStream(tempFile);
            //实例化Excel表格
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 声明一个工作薄   生成一个表格
            //创建工作表单
            String[] sheetNames = {"消息表"};
            for (int i = 0; i < sheetNames.length; i++) {
                workbook.createSheet(sheetNames[i]);
            }
            HSSFSheet sheet = workbook.getSheet(sheetNames[0]);
            // 设置表格第6列列宽度为75个字节
            sheet.setColumnWidth(5,15000);
            //导出到Excel
            ex.exportExcel(sheetNames[0], headers, messageList, out,
                    "yyyy-MM-dd HH:mm", workbook);
            try {
                //保存文件
                workbook.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
            out.close();
            // 以流的形式下载文件。
            File file = new File(path);
            if (file.exists()) {
                OutputStream os = new BufferedOutputStream(response.getOutputStream());
                try {
                    response.setContentType("application/octet-stream");
                    filename = UriUtils.decode(filename, "UTF-8");
                    // 指定下载的文件名
                    response.setHeader("Content-disposition", "attachment; filename= "
                            + new String(filename.getBytes("utf-8"), "ISO8859-1"));
                    FileCopyUtils.copy(new FileInputStream(file), os);
                    return "成功";
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (os != null) {
                        os.close();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();// 删除临时文件
            }
        }
        return "成功";
    }

    @RequestMapping("/formHead")
    public String showHead() {
        return getView("formHead");
    }



}
